#!/usr/bin/env python

# Copyright(c) 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0(the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
import string
import subprocess
import sys


def format(diff):
    filename = None
    changes = {}

    for line in diff.splitlines():
        m = re.search(b'^\+\+\+\ (.*?/)(\S*)', line)
        if m:
            filename = m.group(2)
        if not filename:
            continue

        if not re.match(b'^.*\.(c|h)$', filename):
            continue

        if not filename in changes:
            changes[filename] = []

        m = re.search(b'^@@.*\+(\d+),(\d+)?', line)
        if m:
            start = int(m.group(1))
            end = start + int(m.group(2))
            changes[filename].extend(['-lines', str(start) + ':' + str(end)])

    for filename, lines in changes.items():
        cmd = ['clang-format', filename, '-i', '-style', 'file']
        cmd.extend(lines)
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=None, stdin=subprocess.PIPE)
        stdout, stderr = process.communicate()
        if process.returncode != 0:
            return process.returncode
        process = subprocess.Popen(['git', 'add', filename], stdout=subprocess.PIPE,
                             stderr=None, stdin=subprocess.PIPE)
        stdout, stderr = process.communicate()
        if process.returncode != 0:
            return process.returncode

    return 0

if __name__ == '__main__':
      cmd = ['git', 'diff', '-U1', '--cached', 'HEAD']
      process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                           stderr=None, stdin=subprocess.PIPE)
      out, err = process.communicate()
      if process.returncode != 0:
          sys.exit(process.returncode)
      sys.exit(format(out))
